package cn.cimoc.handler;

import cn.cimoc.model.vo.ResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import cn.cimoc.util.CommonUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LGZ
 * @date 2021/7/25 0025
 * javax.validation参数验证的异常捕获
 */
@ControllerAdvice
public class ValidParamExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) throws JsonProcessingException {
        List<FieldError> fieldErrors = e.getFieldErrors();
        Map<String, String> error = new HashMap<>();
        fieldErrors.forEach((ex)-> error.put(ex.getField(), ex.getDefaultMessage()));
        return CommonUtils.ajaxReturn(error, 400, "参数异常");
    }

}
